package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        if (StringUtils.isBlank(adUserDto.getName())||StringUtils.isBlank(adUserDto.getPassword()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名或密码不能为空");
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDto.getName()));
        if (adUser==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"该用户不存在");
        String password = DigestUtils.md5DigestAsHex((adUserDto.getPassword()+adUser.getSalt()).getBytes());
        if (!adUser.getPassword().equals(password))
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        Map map = new HashMap();
        adUser.setPassword("");
        adUser.setSalt("");
        map.put("user",adUser);
        map.put("token", AppJwtUtil.getToken(Long.valueOf(adUser.getId())));
        return ResponseResult.okResult(map);
    }
}
